﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using NPOI.SS.UserModel;
using RearLivestock.Common.Domains.hq;
using RearLivestock.Common.Domains.wbx;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;

namespace RearLivestock.Beginning.Api.Application.Command.PigBreedings
{
    /// <summary>
    /// 种母配种显示Handler
    /// </summary>
    public class SearchPigsBreedingHandler : IRequestHandler<SearchPigsBreedingCommand, Result<PageResultDto<PigsBreedingDto>>>
    {
        private readonly IMapper mapper;
        /// <summary>
        /// 种母配种
        /// </summary>
        private readonly IBaseRepository<PigsBreeding> pigsBreedingrepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<SearchPigsBreedingHandler> _logger;
        /// <summary>
        /// 栋舍仓储
        /// </summary>
        private readonly IBaseRepository<Bedrooms> bedroomsRepository;

        /// <summary>
        /// 栏位仓储
        /// </summary>
        private readonly IBaseRepository<Fields> fieldrepository;

        /// <summary>
        /// 品种仓储
        /// </summary>
        private readonly IBaseRepository<Varieties> varietiesrepository;
        /// <summary>
        /// 基本信息仓储
        /// </summary>
        private readonly IBaseRepository<BasicInformation> basicInformationrepository;
        /// <summary>
        /// 配种方式
        /// </summary>
        private readonly IBaseRepository<Breedingmethod> breedingmethodrepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="pigsBreedingrepository"></param>
        /// <param name="logger"></param>
        /// <param name="bedroomsRepository"></param>
        /// <param name="fieldrepository"></param>
        /// <param name="varietiesrepository"></param>
        /// <param name="basicInformationrepository"></param>
        /// <param name="breedingmethodrepository"></param>
        public SearchPigsBreedingHandler(IMapper mapper, IBaseRepository<PigsBreeding> pigsBreedingrepository, ILogger<SearchPigsBreedingHandler> logger, IBaseRepository<Bedrooms> bedroomsRepository, IBaseRepository<Fields> fieldrepository, IBaseRepository<Varieties> varietiesrepository, IBaseRepository<BasicInformation> basicInformationrepository, IBaseRepository<Breedingmethod> breedingmethodrepository)
        {
            this.mapper = mapper;
            this.pigsBreedingrepository = pigsBreedingrepository;
            _logger = logger;
            this.bedroomsRepository = bedroomsRepository;
            this.fieldrepository = fieldrepository;
            this.varietiesrepository = varietiesrepository;
            this.basicInformationrepository = basicInformationrepository;
            this.breedingmethodrepository = breedingmethodrepository;
        }
        /// <summary>
        /// 种母配种
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result<PageResultDto<PigsBreedingDto>>> Handle(SearchPigsBreedingCommand request, CancellationToken cancellationToken)
        {
            var result = new Result<PageResultDto<PigsBreedingDto>>() { Code = (int)CommonErrorCode.Search };
            var page = new PageResultDto<PigsBreedingDto>() { TotalCount = 0, PageCount = 0, List = new List<PigsBreedingDto>() };
            try
            {
                var pigsBreeding = await (from a in await pigsBreedingrepository.GetAll()
                                          join b in await basicInformationrepository.GetAll()
                                          on a.BasicInforId equals b.BasicInforId
                                          join c in await varietiesrepository.GetAll()
                                          on b.VarietiesId equals c.VarietiesId
                                          join d in await bedroomsRepository.GetAll()
                                          on a.Transferbuilding equals d.BedroomId
                                          join e in await fieldrepository.GetAll()
                                          on a.Transferfield equals e.FieldId
                                          join f in await breedingmethodrepository.GetAll()
                                          on a.BreedingmethodId equals f.BreedingmethodId
                                          where a.IsDeleted==0
                                          select new PigsBreedingDto()
                                          {
                                              PigsBreedingId=a.PigsBreedingId,
                                              Leader=a.Leader,
                                              LastBreedingDate=a.LastBreedingDate,
                                              BasicInforId = a.BasicInforId,
                                              EarNumber = b.EarNumber,
                                              FatherEarNumber = a.FatherEarNumber,
                                              BreedingmethodId = a.BreedingmethodId,
                                              BreedingmethodName= f.BreedingmethodName,
                                              Estrustype=a.Estrustype,
                                              Firstmatchrating=a.Firstmatchrating,
                                              Currentbuilding = a.Currentbuilding,
                                              Currentfield=a.Currentfield,
                                              Transferbuilding = a.Transferbuilding,
                                              BedroomName=d.BedroomName,
                                              Transferfield = a.Transferfield,
                                              FieldName=e.FieldName,
                                              Reproductivestatus= a.Reproductivestatus,
                                              EventDate= a.EventDate,
                                              DocumentNo= a.DocumentNo,
                                              BreedingWeight= a.BreedingWeight,
                                              VarietiesName = c.VarietiesName
                                          }).ToListAsync();
                //配种时间开始时间查询
                if (request.SDate != null)
                {
                    pigsBreeding = pigsBreeding.Where(x => x.EventDate >= request.SDate).ToList();
                }
                //配种时间结束时间查询
                if (request.ODate != null)
                {
                    pigsBreeding = pigsBreeding.Where(x => x.EventDate <= request.ODate).ToList();
                }
                //负责人模糊查
                if (!string.IsNullOrEmpty(request.Leader))
                {
                    pigsBreeding = pigsBreeding.Where(x => x.Leader.Contains(request.Leader)).ToList();
                }
                page.TotalCount = pigsBreeding.Count();
                page.PageCount = (int)Math.Ceiling(page.TotalCount * 1.0 / request.PageSize);
                page.List = pigsBreeding.OrderBy(x => x.PigsBreedingId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
                result.Data = page;
                result.Msg = "种母配种显示成功";
            }
            catch (Exception ex)
            {
                _logger.LogError("种母配种显示失败" + ex.Message);
                throw;
            }
            return result;
        }
    }
}
